<template>
    <div class="advertisement-add-edit">
        <el-form ref="ad" :model="ad" :rules="rules" label-width="140px">
            <el-form-item label="广告名称：" prop="adName">
                <el-input v-model="ad.adName"></el-input>
            </el-form-item>
            <el-form-item label="所属广告位：" prop="adPos">
                <el-select :disabled="Boolean(id)" v-model="ad.adPos" placeholder="请选择活动区域">
                    <el-option v-for="(adPos, index) in adPosList" :key="index" :label="adPos.ap_name" :value="adPos.ap_id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item v-if="Boolean(id)" label="类别：">
                <el-input :disabled="true" v-model="adPosCate"></el-input>
            </el-form-item>
            <el-form-item label="开始时间：" prop="startTime">
                <el-date-picker
                    v-model="ad.startTime"
                    type="date"
                    placeholder="开始时间">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间：" prop="endTime">
                <el-date-picker
                    v-model="ad.endTime"
                    type="date"
                    placeholder="结束时间">
                </el-date-picker>
            </el-form-item>
            <el-form-item v-if="showWordsInput" label="广告文字：">
                <el-input v-model="ad.words"></el-input>
            </el-form-item>
            <el-form-item v-else label="广告图片上传：">
                <el-upload
                        action="#"
                        :class="{'local-hide': fileList.length >= 1}"
                        :on-change="selectFile"
                        :file-list="fileList"
                        :multiple="false"
                        :limit="1"
                        list-type="picture-card"
                        :auto-upload="false">
                    <i slot="default" class="el-icon-plus"></i>
                    <div slot="file" slot-scope="{file}">
                        <img
                                class="el-upload-list__item-thumbnail"
                                :src="file.url" alt=""
                        >
                        <span class="el-upload-list__item-actions">
        <span
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
                    </div>
                </el-upload>
                <el-dialog :append-to-body="true" :visible.sync="dialogVisible">
                    <img width="100%" :src="dialogImageUrl">
                </el-dialog>
                <span class="desc">系统支持的图片格式为：gif,jpg,jpeg,png</span>
            </el-form-item>
            <el-form-item label="" prop="adv_class_app">
                <el-radio-group v-model="ad.projectScene" @change="handleProjectScene">
                    <el-radio :label="1">H5</el-radio>
                    <el-radio :label="2">小程序</el-radio>
                    <el-radio :label="3">新车团购</el-radio>
                    <el-radio :label="4">售后团购</el-radio>
                    <el-radio :label="6">会员商城</el-radio>
                    <el-radio :label="7">问卷调查</el-radio>
                    <el-radio :label="5">APP</el-radio>
                </el-radio-group>
				<el-select class="adv_class_app" v-model="ad.adv_class_app" v-if="ad.projectScene == 5" placeholder="请选择APP类型">
                  <el-option
                    v-for="item in classAPP"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="if_login" label="限制登录后跳转：">
                <el-radio-group class="if_login" v-model="ad.if_login">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="链接地址：">
                <el-input v-model="ad.link"></el-input>
                <span class="desc">链接地址请不要加http://</span>
				<span class="desc red">积分商城小程序必须添加https://</span>
            </el-form-item>
            <el-form-item label="幻灯片排序：">
                <el-input v-model="ad.sort"></el-input>
                <span class="desc">数字越小排序越靠前</span>
            </el-form-item>
            <el-form-item class="btn-wrapper">
                <el-button @click="$emit('cancel')">取消</el-button>
                <el-button type="primary" @click="submitAd('ad')">确定</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
	import {dateFormatter} from "../../../../common/js/util";

	export default {
		data() {
			return {
				fileList: [],
				dialogImageUrl: '',
				dialogVisible: false,
				adPosCate: '',
				adPosList: [],
				ad: {
					adName: '',
					adPos: '',
					startTime: '',
					endTime: '',
					link: '',
					sort: '',
					words: '',
					projectScene: 1,
					adv_class_app: '',
					if_login: 0
				},
				classAPP: [
					{label: 'APP原生', value: 1},
					{label: '元通汽车小程序', value: 2},
					{label: '积分商城小程序', value: 3},
					{label: 'H5', value: 4}
				],
				rules: {
					adName: [
						{ required: true, message: '请输入广告名称', trigger: 'blur' }
					],
					adPos: [
						{ required: true, message: '请选择所属广告位', trigger: 'change' }
					],
					startTime: [
						{ type: 'date', required: true, message: '请选择开始时间', trigger: 'change' }
					],
					endTime: [
						{ type: 'date', required: true, message: '请选择结束时间', trigger: 'change' }
					],
					adv_class_app: [
						{ required: false, message: '请选择APP类型', trigger: 'change' }
					],
					if_login: [
						{ required: true, message: '请选择跳转限制', trigger: 'change' }
					],
					sort: [
						{ type: 'number', message: '幻灯片排序必须为数字', trigger: 'blur' }
					]
				}
			}
		},
		props: {
			id: {
				type: Number,
				default: 0
			}
		},
		computed: {
			showWordsInput() {
				if (!this.ad.adPos || !this.adPosList.length) {
					return false;
				} else {
					let adPosItem = this.adPosList.find(item => item.ap_id == this.ad.adPos) || {};
					return adPosItem.ap_class == 1
				}
			}
		},
		methods: {
			getAdDetail(id) {
				this.$http.post('/admin/advertising/index.php?act=advManager&op=getAdvById', {
					adv_id: id
				}).then(res => {
					if (res.code == 1) {
						this.ad.adName = res.data.adv_title;
						this.ad.adPos = res.data.ap_id * 1;
						this.ad.startTime = new Date(res.data.adv_start_date * 1000);
						this.ad.endTime = new Date(res.data.adv_end_date * 1000);
						this.ad.link = res.data.adv_content.url;
						this.ad.sort = res.data.slide_sort * 1;
						this.ad.projectScene = res.data.adv_class * 1
						this.adPosCate = this.computeCateText(res.data.ap_class * 1);
						if (res.data.ap_class == 1) {
							this.ad.words = res.data.adv_content.adv_word
						} else {
							this.fileList.push({
								url: res.data.adv_content.adv_pic ? res.data.adv_content.adv_pic : (res.data.adv_content.adv_slide_pic ? res.data.adv_content.adv_slide_pic : res.data.adv_content.flash_swf)
							});
						}
						this.ad.adv_class_app = Number(res.data.adv_class_app)
						this.ad.if_login = Number(res.data.if_login)
						this.handleProjectScene(this.ad.projectScene)
					} else {
						alert(res.msg);
					}
				})
			},
			handleProjectScene(val) {
				if (val == 5) {
					this.rules.adv_class_app[0].required = true
				} else {
					this.rules.adv_class_app[0].required = false
					this.ad.adv_class_app = ''
					this.$refs['ad']['clearValidate']('adv_class_app')
				}
			},
			computeCateText(val) {
				switch (val) {
					case 0:
						return '图片'
						break
					case 1:
						return '文字'
						break
					case 2:
						return '幻灯'
						break
					case 3:
						return 'Flash'
						break
				}
			},
			handleRemove(file) {
				let index = this.fileList.findIndex(item => item.url == file.url);
				this.fileList.splice(index, 1);
			},
			handlePictureCardPreview(file) {
				this.dialogImageUrl = file.url;
				this.dialogVisible = true;
			},
			selectFile(file, fileList) {
				this.fileList = fileList;
			},
			getAdPosList() {
				this.$http.get('/admin/advertising/index.php?act=advManager&op=getApList').then(res => {
					if (res.code == 1) {
						if (res.data && res.data.length) {
							this.adPosList = res.data.map(item => ({
								ap_id: item.ap_id * 1,
								ap_name: item.ap_name,
								ap_class: item.ap_class * 1,
							}));
						} else {
							this.adPosList = [];
						}
					}
					else if (res.code == 1000) {
						this.adPosList = [];
					}
					else {
						alert(res.msg);
					}
				})
			},
			submitAd(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						let startTime = this.ad.startTime;
						let endTime = this.ad.endTime;
						if (endTime.getTime() < startTime.getTime()) {
							this.$message({
								message: '开始时间必须在结束时间之前',
								type: 'error'
							});
							return
						}
						let data = new FormData();
						data.append('adv_name', this.ad.adName);
						data.append('adv_start_date', dateFormatter('YYYY-MM-DD', startTime));
						data.append('adv_end_date', dateFormatter('YYYY-MM-DD', endTime));
						data.append('adv_pic_url', this.ad.link);
						data.append('adv_class_app', this.ad.adv_class_app);
						data.append('if_login', this.ad.if_login);
						if (this.ad.sort && isNaN(this.ad.sort)) {
							this.$message({
								message: '幻灯片排序必须为数字',
								type: 'error'
							});
							return
						}
						data.append('adv_class', this.ad.projectScene);
						data.append('slide_sort', this.ad.sort);
						let adPosItem = this.adPosList.find(item => item.ap_id == this.ad.adPos);
						data.append('ap_class', adPosItem.ap_class);
						if (adPosItem.ap_class == 1) {
							data.append('adv_word', this.ad.words);
						} else {
							if (this.fileList.length) {
								let images = this.fileList.map(function(item) {
									return item.raw ? item.raw : item.url;
								});
								for (let i=0; i<images.length; i++) {
									data.append('adv_pic', images[i]);
								}
							}
						}
						if (this.id && this.id) {
							// 编辑
							data.append('adv_id', this.id);
						} else {
							// 新增
							data.append('ap_id', this.ad.adPos);
						}
						this.$http.post('/admin/advertising/index.php?act=advManager&op=operateAdvInfo', data).then(res => {
							if (res.code == 1) {
								let message = '';
								if (this.id) {
									message = '编辑成功'
								} else {
									message = '新增成功'
								}
								this.$message({
									message: message,
									type: 'success'
								});
								this.$emit('addEditSuccess');
								this.$emit('cancel')
							}
							else {
								alert(res.msg);
							}
						})
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			}
		},
		created() {
			if (this.id) {
				this.getAdDetail(this.id);
			}
			this.getAdPosList();
		},
		name: "advertisement-add-edit"
	}
</script>

<style lang="scss" scoped>
    .advertisement-add-edit {
        padding: 0 20px;
    }
	.red {
	color: #c00;
	}
    /deep/ .el-form-item {
        padding-top: 8px;
        .el-form-item__content {
            display: flex;
            align-items: center;
            .el-input {
                width: 400px;
            }
            .desc {
                margin-left: 30px;
            }
			.adv_class_app { 
				margin-left: 10px;
				.el-input {
				    width: 150px;
				}
			}
        }
		.if_login {
			padding-top: 7px;
		}
    }
    /deep/ .local-hide .el-upload--picture-card {
        display: none;
    }
</style>
